package com.hdoit.pisces.web.rel.controllers;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hdoit.pisces.logical.rel.model.Event;
import com.hdoit.pisces.logical.rel.model.Relationship;
import com.hdoit.pisces.logical.rel.model.Relative;
import com.hdoit.pisces.logical.rel.service.IEventService;
import com.hdoit.pisces.logical.rel.service.IRelationshipService;
import com.hdoit.pisces.logical.rel.service.IRelativeService;
import com.hdoit.pisces.logical.viewmodel.RelationshipSearch;
import com.hdoit.pisces.logical.viewmodel.RelativeSearch;
import com.tennetcn.common.enums.ManageContainer;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.logical.superbase.service.IEmployeeService;
import com.tennetcn.common.logical.superbase.service.IRoleEmployeeService;
import com.tennetcn.common.logical.superbase.service.IRoleService;
//import com.tennetcn.common.enums.pub.SexStatus;
import com.tennetcn.common.message.PagerModel;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.component.web.ActionResult;
import com.tennetcn.component.web.BaseController;
import com.tennetcn.component.web.ErrorResult;
import com.tennetcn.web.cbase.AuthPassport;

@Controller
@RequestMapping(value="/admin/rel/relative")
public class RelativeController extends BaseController{

	private static final String[] relativeManageViewName = null;

	@Override
	public String getRoutePath() {
		return "areas/admin/rel/relative/";
	}
	
	private IEmployeeService employeeService;

	private IEventService eventService;
	private IRelativeService relativeService;
	private IRoleEmployeeService roleEmployeeService;
	private IRelationshipService relationshipService;
	private final String indexViewName="index";
	private final String outputViewName="output";
	private final String detailedViewName="relativeDetailed";
	private final String saveViewName="save";
	private final String bsFileUploadViewName="bsFileUpload";
	private final String relativeInfoViewName="relative_info";
	private final String saveIntroViewName="save_intro";
	private final String editEventViewName="edit_event";
	private final String saveEventViewName="save_event";
	private final String uploadViewName="upload";
	private final String relativeListViewName="relative_list";
	private final String relativeManagerViewName="manager/index";
	private final String relativeAddViewName="relative_add_save";
	private final String eventViewName="relative_event";
	private Relative rel;

	//private final String addViewName="add_save";
	//private final String ="";


	
	public IEmployeeService getEmployeeService() {
		return employeeService;
	}

	@Resource
	public void setEmployeeService(IEmployeeService employeeService) {
		this.employeeService = employeeService;
	}
	
	public IEventService getEventService() {
		return eventService;
	}

	@Resource
	public void setEventService(IEventService eventService) {
		this.eventService = eventService;
	}
	
	
	public IRelativeService getRelativeService(){
		return relativeService;
	}
	
	@Resource
	public void setRelativeService(IRelativeService relativeService){
		this.relativeService=relativeService;
	}
	
	
	public IRoleEmployeeService getRoleEmployeeService(){
		return roleEmployeeService;
	}
	
	@Resource
	public void setRoleEmployeeService(IRoleEmployeeService roleEmployeeService){
		this.roleEmployeeService = roleEmployeeService;
	}
	
	
	
	
	public IRelationshipService getRelationshipService() {
		return relationshipService;
	}
	@Resource
	public void setRelationshipService(IRelationshipService relationshipService) {
		this.relationshipService = relationshipService;
	}

	private IRoleService roleService;
	
	public IRoleService getRoleService(){
		return roleService;
	}
	
	@Resource
	public void setRoleService(IRoleService roleService){
		this.roleService = roleService;
	}
	
	

	
	@RequestMapping(value=indexViewName,method={RequestMethod.GET,RequestMethod.POST})
	public String index(Model model,RelativeSearch relativeSearch,PagerModel pagerModel,boolean ajaxPost){
		
		List<Relative> relatives=relativeService.queryList(relativeSearch);
		//List<RoleEmployee>role_employees=roleEmployeeService.queryList(search);
		
		//List<Employee> employees = employeeService.queryList(search);
		
		String key = getLoginModel().getLoginId();
		
		String userKey = roleService.queryModelByMark("3").getRoleId();//普通用户
		String managerKey = roleService.queryModelByMark("2").getRoleId();//普通管理员
		//roleService.queryModel(userKey)
		
		//List<Relationship> relationships=relationshipService.queryList(relationshipSearch);
		
		//List<RoleEmployee>role_employees=roleEmployeeService.queryList(search);
		
	//	Relationship relationship = new Relationship();
		
		if(roleEmployeeService.queryRoleIdsByEmployeeId(key).equals(userKey)){
			//普通用户
			for(int i = relatives.size()-1; i >=0;i--){
				if(! relationshipService.queryModel((relatives.get(i).getRelativeId()))
								.getEmployeeId()
								.equals(key)){
					relatives.remove(i);
				}
			}
			pagerModel.setTotalAmount(relatives.size());
			
		}else if(roleEmployeeService.queryRoleIdsByEmployeeId(key).equals(managerKey)){
			//普通管理员
			for(int i = relatives.size()-1; i >=0;i--){
				if(!roleService.queryModel(roleEmployeeService
											.queryModel(relationshipService.queryModel((relatives.get(i).getRelativeId()))
											.getEmployeeId())
											.getRoleId()).getRoleMark().equals("2")){
					relatives.remove(i);
				}
			}
			pagerModel.setTotalAmount(relatives.size());
			
		}else{
			//超级管理员
		//	List<Relationship> relationships=relationshipService.queryList(relationshipSearch);
			pagerModel.setTotalAmount(relativeService.queryCount(relativeSearch));
		}
	
		
		
	//	model.addAttribute("employees", employees);
		//model.addAttribute("employeeSearch",search);
		
	//	model.addAttribute("sessionWebFactory", sessionWebFactory);
		
		//model.addAttribute("role_employees", role_employees);
		
		model.addAttribute("relatives",relatives);
		model.addAttribute("relativeSearch",relativeSearch);
		model.addAttribute(ManageContainer.PAGERKEY,pagerModel);
		
		if(ajaxPost){
			return view(outputViewName);
		}
		return view(indexViewName);
	}
	
	@RequestMapping(value=detailedViewName,method={RequestMethod.GET,RequestMethod.POST})
	public String relativeDetailed(Model model,String key){
		Relative relative=new Relative();
		//relative.setRelative_sex(SexStatus.male);
		
		if(!StringUtils.isEmpty(key)){
			relative=relativeService.queryModel(key);
		}
		model.addAttribute("relative",relative);
		return view(detailedViewName);
	}
	
	@RequestMapping(value=saveViewName,method={RequestMethod.POST})
	public String save(Model model,Relative relative){
//		if(StringUtils.isEmpty(relative.getRelativeId())){
			relative.setRelativeId(CommonUtils.getKeyId());
			
			//relative.setCreateDate(DateUtils.getCurrent());
//			relative.setCreateUserId(getLoginModel().getLoginId());
//			relative.setCreateUserName(getLoginModel().getLoginName());
			
			//System.out.println("relativeId is :"+relative.getRelativeId());
//			Relationship relationship=new Relationship();
//			relationship.setRelativeId(relative.getRelativeId());
//			relationship.setModelStatus(ModelStatus.add);
//		}else{
//			student.setModifyDate(DateUtils.getCurrent());
//			student.setModifyUserId(getLoginModel().getLoginId());
//			student.setModifyUserName(getLoginModel().getLoginName());
//			relative.setModelStatus(ModelStatus.update);
//		}
//		relative.setMarkCode(ChineseUtils.getPinYinHeadChar(relative.getRelative_name()));
//		relative.setCode(ChineseUtils.getPingYin(relative.getRelative_name()));
		Relationship relationship =new Relationship();
		relationship.setRelationshipId(CommonUtils.getKeyId());
		relationship.setRelativeId(relative.getRelativeId());
		relationship.setRelative_firstName(relative.getRelative_firstName());
		relationship.setRelative_lastName(relative.getRelative_lastName());
		relationship.setEmployeeId(getLoginModel().getLoginId());
		relationship.setEmployeeName(getLoginModel().getLoginName());
		relative.setModelStatus(ModelStatus.add);
		//relativeService.addModel(relative);
		relationshipService.addModel(relationship);
		
		
		ActionResult actionResult;
        if(relativeService.applyChange(relative)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("relative", relative);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);
		
		return view(detailedViewName); 
	}
	@RequestMapping(value = bsFileUploadViewName, method = { RequestMethod.GET })
	public String bsFileUpload(Model model){
		return view(bsFileUploadViewName);
	}

	
	@RequestMapping(value = "relative_add", method = { RequestMethod.GET })
	public String test(Model model){
		return view("relative_add");
	}
	

	@RequestMapping(value=relativeInfoViewName,method={RequestMethod.GET,RequestMethod.POST})
	@AuthPassport
	public ModelAndView index(Model model,String key){
		
		rel=relativeService.queryModel(key);


		/*List<String> images=getImages();*/
//		List<String> audios=getAudios();
//		List<String> videos=getVideos();

		if(!model.containsAttribute("events")){
			List<Event> events;
			Event event=new Event();
			event.setRelativeId(rel.getRelativeId());

			events=eventService.queryList(event);
			model.addAttribute("events",events);	
		}
		
		model.addAttribute("relative",rel);	
		/*model.addAttribute("images",images);*/
//		model.addAttribute("audios",audios);
//		model.addAttribute("videos",videos);
		//model.addAttribute("comments",rel.getComments());
		return new ModelAndView("redirect:../../xln?num="+rel.getRelativeId());
	}
	
	
	@RequestMapping(value="getimage", method ={RequestMethod.GET,RequestMethod.POST})
    public void getPic(HttpServletRequest request,HttpServletResponse response,String path) throws Exception {
        response.setContentType("image/jpg");  
        response.setCharacterEncoding("utf-8");
        

        try {
            URL url = new URL(path);
            BufferedInputStream bis = new BufferedInputStream(url.openStream());
            byte[] bytes = new byte[100];
            OutputStream out = response.getOutputStream();
            int len;
            while ((len = bis.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
            bis.close();
            out.flush();
            out.close();

        } catch (Exception e) {

        }   
    } 

	@RequestMapping(value=saveIntroViewName,method={RequestMethod.GET,RequestMethod.POST})
	@AuthPassport
	public ModelAndView saveIntro(Model model,Relative relative){
		if(StringUtils.isEmpty(relative.getRelativeId())){
			relative.setRelativeId(CommonUtils.getKeyId());	
			relative.setModelStatus(ModelStatus.add);
		}else{
			relative.setModelStatus(ModelStatus.update);
		}		
		ActionResult actionResult;
		if(relativeService.applyChange(relative)){
	            actionResult=new ActionResult();
	        }else{
	            actionResult=new ErrorResult();
	        }
		
		model.addAttribute(ManageContainer.RESULTKEY, actionResult);
		return new ModelAndView("redirect:../../xln?num="+relative.getRelativeId());
	}
	
	@RequestMapping(value=saveEventViewName,method={RequestMethod.GET,RequestMethod.POST})
	@AuthPassport
	public ModelAndView saveEvent(Model model,HttpServletRequest request,boolean ajaxPost){
		String[] dates=request.getParameterValues("event_date");
		String[] infos=request.getParameterValues("event_info");
		String[] ids=request.getParameterValues("event_id");
		String relativeId=request.getParameter("relative_id");
		for(int i=0;i<ids.length;i++){
			Event e=new Event();
			try {
				e.setEventDate(new SimpleDateFormat("yyyy-MM-dd").parse(dates[i]));
			} catch (ParseException e1) {
			}

				
			if(ids[i].length()<2){
				e.setModelStatus(ModelStatus.add);
				e.setEventId(CommonUtils.getKeyId());
			}else if(infos[i].length()<1){
				e.setModelStatus(ModelStatus.delete);
				
			}else{
				e.setModelStatus(ModelStatus.update);
				e.setEventId(ids[i]);
			}
			e.setRelativeId(relativeId);
			e.setEventInfo(infos[i]);
			
			eventService.applyChange(e);				
		}
		
		System.out.println("\n-------------------------------------\nRECEIVE IT!");
		for(int i=0;i<dates.length;i++){
			System.out.println("\n-------------------------------------\n"
					+"          "+i+"\n"
					+dates[i]+"\n-------------------------------------\n"
					+infos[i]+"\n-------------------------------------\n"
					+ids[i]+"\n-------------------------------------\n");
		}
		
		
		/*
		for(int i=1;i<7;i++){
			Event e=new Event();
			e.setEventDate(DateUtils.getCurrent());
			e.setEventInfo("test event-"+i);
			events.add(e);
		}	
		model.addAttribute("events", events);*/
		
		return new ModelAndView("redirect:../../xln?num="+relativeId);		
	}
	
	
	
/*	//@RequestMapping(value=editEventViewName,method={RequestMethod.GET,RequestMethod.POST})
	public String editEvent(Model model,String key,String relativeId){
		Event event=new Event();
		
		if(!StringUtils.isEmpty(key)){
			event=eventService.queryModel(key);
		}else{
			event.setRelativeId(relativeId);
		}
		
		model.addAttribute("event",event);		
		return view(editEventViewName);
	}*/

	@RequestMapping(value=relativeAddViewName,method={RequestMethod.GET,RequestMethod.POST})
	public ModelAndView add(Model model,HttpServletRequest request){
		
		Relative relative=new Relative();
		relative.setRelative_alive(request.getParameter("relative_alive"));
		try {
			relative.setRelative_birthday(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("relative_birthday")));
			relative.setRelative_deathday(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("relative_deathday")));
		} catch (ParseException e) {
		} catch (NullPointerException e){
			
		}
		relative.setRelative_buryAddress(request.getParameter("relative_buryAddress"));
		relative.setRelative_city(request.getParameter("relative_city"));
		relative.setRelative_firstName(request.getParameter("relative_firstName"));
		relative.setRelative_lastName(request.getParameter("relative_lastName"));
		relative.setRelative_information(request.getParameter("relative_information"));
		relative.setRelative_job(request.getParameter("relative_job"));
		relative.setRelative_nation(request.getParameter("relative_nation"));
		relative.setRelative_province(request.getParameter("relative_province"));
		relative.setRelative_sex(request.getParameter("relative_sex"));
		relative.setRelative_alive(request.getParameter("relative_alive"));
		relative.setRelativeId(CommonUtils.getKeyId());
		String tmpRelId=relative.getRelativeId();
		relative.setModelStatus(ModelStatus.add);
		relativeService.applyChange(relative);

		
		
		Relationship relation=new Relationship();
		relation.setRelationshipId(CommonUtils.getKeyId());
		String tmpRetId=relation.getRelationshipId();
		relation.setEmployeeId(getLoginModel().getLoginId());
		relation.setEmployeeName(getLoginModel().getLoginName());;
		relation.setRelationship(request.getParameter("relative_relation"));
		relation.setRelativeId(tmpRelId);
		relation.setRelative_firstName(relative.getRelative_firstName());
		relation.setRelative_lastName(relative.getRelative_lastName());
		relation.setModelStatus(ModelStatus.add);
		relationshipService.applyChange(relation);
		
		String[] dates=request.getParameterValues("event_date");
		String[] infos=request.getParameterValues("event_info");
		//String[] ids=request.getParameterValues("event_id");
		String relativeId=request.getParameter("relative_id");
		for(int i=0;i<dates.length;i++){
			Event e=new Event();
			try {
				e.setEventDate(new SimpleDateFormat("yyyy-MM-dd").parse(dates[i]));
			} catch (ParseException e1) {
				
			}
			e.setRelativeId(tmpRelId);
		
			e.setEventInfo(infos[i]);
			e.setEventId(CommonUtils.getKeyId());	
			e.setModelStatus(ModelStatus.add);
			eventService.applyChange(e);	
			//eventService.addModel(e);
			//model.addAttribute("", employee);
		}
		
//		relationshipService.addModel(relation);
//		relativeService.addModel(relative);
//		model.addAttribute("employee", employee);
//		model.addAttribute("employee", employee);
		
					
		return new ModelAndView("redirect:../../mainnew");	
	}
	
	@RequestMapping(value=relativeListViewName,method={RequestMethod.GET,RequestMethod.POST})
	public String getRelativeList(Model model,RelationshipSearch search,PagerModel pagerModel){
		
		/*String tempKey=getLoginModel().getLoginId();
		List<Relationship> relations=relationshipService.queryList(search);
		model.addAttribute("relations",relations);			
		return view(relativeManagerViewName);*/
		String employeeId=getLoginModel().getLoginId();		
		String mark=roleService.queryModel(roleEmployeeService.queryRoleIdsByEmployeeId(employeeId).get(0)).getRoleMark();
		System.out.println(mark);
		if(mark.equals("1")||mark.equals("2")){
			pagerModel.setTotalAmount(relationshipService.queryCount(search));
			List<Relationship> relations=relationshipService.queryList(search);
			
			model.addAttribute("relations",relations);
			model.addAttribute("relationSearch",search);
			model.addAttribute(ManageContainer.PAGERKEY,pagerModel);
			System.out.println("4364274627426427");
			return view(relativeManagerViewName);
		}
		

		search.setSearchKey(employeeId);
		List<Relationship> relations=relationshipService.queryList(search);
		List<String> images=new ArrayList<>();
		for(int i=0;i<relations.size();i++){
			String s=relativeService.queryModel(relations.get(i).getRelativeId()).getRelative_file()+"images/photo.jpg";
			images.add(s);
		}
		model.addAttribute("relations",relations);	
		model.addAttribute("images",images);	
		return view(relativeListViewName);
	
	}
	
	@RequestMapping(value=relativeManagerViewName,method={RequestMethod.GET,RequestMethod.POST})
	public String getRelativeManagerList(Model model,RelationshipSearch search,PagerModel pagerModel,boolean ajaxPost){

		pagerModel.setTotalAmount(relationshipService.queryCount(search));
		List<Relationship> relations=relationshipService.queryList(search);
		
		model.addAttribute("relations",relations);
		model.addAttribute("relationSearch",search);
		model.addAttribute(ManageContainer.PAGERKEY,pagerModel);
		if(ajaxPost){
			System.out.println("1111111111166666666666");
			return view("/manager/"+outputViewName);
		}
		System.out.println("0000000000000000000000000000");
		return view("/manager/"+indexViewName);
	}
	
	/*@RequestMapping(value=relativeManageViewName,method={RequestMethod.GET,RequestMethod.POST})
	public String index(Model model,RelativeSearch relativeSearch,PagerModel pagerModel,boolean ajaxPost){
		
		pagerModel.setTotalAmount(relativeService.queryCount(relativeSearch));
		List<Relative> relatives=relativeService.queryList(relativeSearch);
		
		model.addAttribute("relatives",relatives);
		model.addAttribute("relativeSearch",relativeSearch);
		model.addAttribute(ManageContainer.PAGERKEY,pagerModel);
		
		if(ajaxPost){
			return view(outputViewName);
		}
		return view(indexViewName);
	}*/
	
	@RequestMapping(value=uploadViewName,method={RequestMethod.GET,RequestMethod.POST})
	public String upload(Model model){
		return view(editEventViewName);
	}
	
	

	
	
	
	
	
	/*private List<String> getImages(){
		String path = "H:/111/"+rel.getRelativeId();
		File folder = new File(path);
        if (!folder.exists())
        	folder.mkdirs();  
		File temp[] = folder.listFiles();
		List<String> picPaths = new ArrayList();
		for (int i = 0; i < temp.length; i++) {
			picPaths.add(path+"/"+temp[i].getName());
		}
		return picPaths;
	}*/
	
//	private ArrayList<String> getAudios(String path){
//		ArrayList<String> ans=new ArrayList<String>();
//		if(path!=null){
//		ans.add(path+"musics/1.mp3");
//		ans.add(path+"musics/1.mp3");
//		ans.add(path+"musics/1.mp3");
//		ans.add(path+"musics/1.mp3");
//		}
//		return ans;
//	}
	
//	private ArrayList<String> getVideos(String path){
//		ArrayList<String> ans=new ArrayList<String>();
//		if(path!=null){
//		ans.add(path+"videos/1.mp4");
//		ans.add(path+"videos/1.mp4");
//		ans.add(path+"videos/1.mp4");
//		ans.add(path+"videos/1.mp4");
//		}
//		return ans;
//	}
	
	
	
}
	
	
